package com.xbq.exceleditor.ui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.gyf.immersionbar.ktx.immersionBar
import com.xbq.exceleditor.MainActivity
import com.xbq.exceleditor.OFFICE_TYPE
import com.xbq.exceleditor.R
import com.xbq.exceleditor.adapter.HomeJingxuanVideoAdapter
import com.xbq.exceleditor.adapter.TemplateAdapter
import com.xbq.exceleditor.bean.viewmodel.HomeViewModel
import com.xbq.exceleditor.databinding.FragmentHomeBinding
import com.xbq.exceleditor.db.ExcelDatabase
import com.xbq.exceleditor.ui.excel.ExcelActivity
import com.xbq.exceleditor.ui.filechooser.FileChooserActivity
import com.xbq.exceleditor.ui.filechooser.media.FileTypeEnum
import com.xbq.exceleditor.utils.ensureCopyFile
import com.xbq.exceleditor.utils.ensureLoginClick
import com.xbq.exceleditor.utils.ensureStoragePermission
import com.xbq.exceleditor.utils.ensureVipClick
import com.xbq.xbqsdk.component.activity.VBFragment
import com.xbq.xbqsdk.component.recyleview.GridSpaceDecoration
import com.xbq.xbqsdk.component.recyleview.LinearSpaceDecoration
import com.xbq.xbqsdk.core.ext.ensureLogin
import com.xbq.xbqsdk.net.officeeditor.OfficeEditorApi
import com.xbq.xbqsdk.net.officeeditor.dto.VideosByTypeDto
import com.xbq.xbqsdk.util.activityresult.StartActivityForResultHelper
import com.xbq.xbqsdk.util.click.onDebouncedClick
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject


/**
 * Author: liaohaiping
 * Time: 2020-10-24
 * Description:
 */
@AndroidEntryPoint
class HomeFragment : VBFragment<FragmentHomeBinding>() {
    @Inject
    lateinit var templateAdapter: TemplateAdapter

    @Inject
    lateinit var officeEditorApi: OfficeEditorApi

    @Inject
    lateinit var homeJingxuanVideoAdapter: HomeJingxuanVideoAdapter
    val viewModel: HomeViewModel by viewModels()

    @Inject
    lateinit var db: ExcelDatabase


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.tvAppName.text = AppUtils.getAppName()
        initRecyclerView(binding)
        initClickListener(binding)
        loadJingxuanVideos()
        loadTemplates()
        viewModel.init()
    }

    private fun loadTemplates() {
        val files = context?.assets?.list("templates")
        var results = arrayListOf<String>()
        files?.let {
            for (file in it) {
                if (file.endsWith(".png")) {
                    results.add(file)
                }
            }
        }
        results.shuffle(Random(requireContext().packageName.hashCode().toLong()))
        var sublist = results.subList(0, 4)
        templateAdapter.setList(sublist)

    }

    override fun onResume() {
        super.onResume()
        immersionBar {
            titleBar(R.id.toolbar)
            statusBarDarkFont(true)
        }
    }


    private fun initClickListener(it: FragmentHomeBinding) {
        it.btnJichu.ensureLoginClick(requireActivity()) {
            if (viewModel.collections.size > 0) {
                PlayVideoActivity.start(viewModel.collections.get(0))
            }
        }
        it.btnXingzheng.ensureLoginClick(requireActivity()) {
            if (viewModel.collections.size > 1) {
                PlayVideoActivity.start(viewModel.collections.get(1))
            }
        }
        it.btnPaiban.ensureLoginClick(requireActivity()) {
            if (viewModel.collections.size > 2) {
                PlayVideoActivity.start(viewModel.collections.get(2))
            }
        }
        it.btnWenmi.ensureLoginClick(requireActivity()) {
            if (viewModel.collections.size > 3) {
                PlayVideoActivity.start(viewModel.collections.get(3))
            }
        }
        it.btnShortcutKey.onDebouncedClick {
            ActivityUtils.startActivity(ShortcutKeyActivity::class.java)
        }

        it.btnViewMoreTemplates.onDebouncedClick {
            (activity as MainActivity?)?.showTemplateFragment()
        }

        it.btnNewDocument.ensureVipClick(requireActivity(), "newDocument") {
            ensureStoragePermission("存储权限：用于保存Excel文档到SD卡中，避免因清除缓存导致文档丢失") {
                ActivityUtils.startActivity(ExcelActivity::class.java)
            }
        }

        it.btnMyDocument.ensureLoginClick(requireActivity()) {
            ensureStoragePermission("存储权限：用于读取保存到SD卡中的Excel文档") {
                ActivityUtils.startActivity(MyDocumentActivity::class.java)
            }
        }

        it.btnOpenLocalFile.ensureVipClick(requireActivity(), "openLocalFile") {
            ensureStoragePermission("存储权限：用于读取SD卡中的Excel文档，供您选择打开") {
                FileChooserActivity.startForResult(
                    requireActivity(),
                    FileTypeEnum.XLSX
                ) { resultCode, data ->
                    if (resultCode == Activity.RESULT_OK) {
                        FileChooserActivity.getResult(data)?.let {
                            ExcelActivity.startEdit(it.absolutePath)
                        }
                    }
                }
            }

        }
    }


    fun openXlsxChooser() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.setType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//无类型限制
//        intent.setType("file/*");//无类型限制
        intent.putExtra(
            Intent.EXTRA_MIME_TYPES,
            arrayOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        )
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)
//        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//多选
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        val chooser = Intent.createChooser(intent, "选择Excel文件")
        StartActivityForResultHelper.startActivityForResult(this, chooser) { resultCode, data ->
            if (resultCode == Activity.RESULT_OK) {
                data.data?.let {
                    ExcelActivity.startEdit(UriUtils.uri2File(it).absolutePath)
                }

            }
        }

    }

    private fun initRecyclerView(it: FragmentHomeBinding) {
        it.templateList.layoutManager = GridLayoutManager(context, 2)
        it.templateList.addItemDecoration(GridSpaceDecoration(2, 8f))
        it.templateList.adapter = templateAdapter
        templateAdapter.setOnItemClickListener { ad, view, position ->
            ensureStoragePermission("存储权限：用于保存编辑后的Excel文档至SD卡中，避免因清除缓存导致文档丢失") {
                val item = templateAdapter.getItem(position)
                val xlsxFile = requireContext().ensureCopyFile(item)
                ExcelActivity.startEdit(xlsxFile.absolutePath)
            }
        }



        it.videoList.layoutManager = LinearLayoutManager(context)
        it.videoList.addItemDecoration(LinearSpaceDecoration(4f))
        it.videoList.adapter = homeJingxuanVideoAdapter
        homeJingxuanVideoAdapter.setOnItemClickListener { ad, view, position ->
            ensureLogin {
                val item = homeJingxuanVideoAdapter.getItem(position)
                PlayVideoActivity.start(item)
            }
        }

    }

    private fun loadJingxuanVideos() {
        lifecycleScope.launch {
            val res = officeEditorApi.videos_by_type(VideosByTypeDto(OFFICE_TYPE, "精选", 6))
            if (res.success()) {
                var list = res.data!!
                homeJingxuanVideoAdapter.setList(list)
            } else {
                ToastUtils.showShort(res.message)
            }
        }
    }


}